package payment.mobilepos.unionpay.com.metroguide.utils;

import android.content.Context;
import android.content.res.AssetManager;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import payment.mobilepos.unionpay.com.metroguide.ui.Stations;

import static com.alibaba.fastjson.JSON.parseArray;

/**
 * <pre>
 *     author : liuso
 *     e-mail : xxx@xx
 *     time   : 2018/12/25
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class JsonParser {

    public static String parseIatResult(String json) {
        StringBuffer ret = new StringBuffer();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词，默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
//				如果需要多候选结果，解析数组其他字段
//				for(int j = 0; j < items.length(); j++)
//				{
//					JSONObject obj = items.getJSONObject(j);
//					ret.append(obj.getString("w"));
//				}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret.toString();
    }


    static Map<String, String> keymap = new HashMap<>();
    static Map<String, String> Valuemap = new HashMap<>();

    public static Map getJson(Context context, boolean keyorValue) {
        if (keyorValue && keymap.size() != 0) return keymap;
        if ((!keyorValue) && Valuemap.size() != 0) return Valuemap;
        String fileName = "stations.json";
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Stations> stations = parseArray(stringBuilder.toString(), Stations.class);
        for (Stations station : stations) {
            Valuemap.put(station.getValue(), station.getKey());
            keymap.put(station.getKey(), station.getValue());
        }
        return keyorValue ? keymap : Valuemap;
    }

}
